package io.mft.yapi.function;

import org.junit.Test;

import cn.hutool.core.util.ObjectUtil;
import io.mft.api.domain.ExecutingResource;
import io.mft.api.domain.Regulation;
import io.mft.commons.exception.MFTException;
import io.mft.commons.function.ExecuteReturn;
import io.mft.commons.function.response.kv.KVMap;
import io.mft.dev.base.BaseFunction;
import io.mft.plugin.PAFunction;
import io.mft.plugin.PluginContext;
import io.mft.plugin.tester.PluginFunctionTester;
import io.mft.yapi.util.YApiAccount;
import io.mft.yapi.util.YApiManager;
import lombok.extern.slf4j.Slf4j;

@PAFunction(value = "MFTAsExportToYapi", note = "API接口元数据导入到YAPI接口平台")
@Slf4j
public class MFTAsExportToYapiFunction extends BaseFunction {

	@Override
	public ExecuteReturn doExecute(PluginContext<ExecutingResource<Regulation>> context) {
		String funcNo = context.getRequest().getString("funcNo", "");// 功能号
		String systemKey = context.getRequest().getString("systemKey", "");
		String moduleKey = context.getRequest().getString("moduleKey", "");
		String loginId = context.getRequest().getString("loginId", "");
		String pass = context.getRequest().getString("pass", "");
		String token = context.getRequest().getString("token", "");
		KVMap kv = new KVMap();
		kv.set("yApi.YApiLoginEmail", loginId);
		kv.set("yApi.YApiPassword", pass);
		kv.set("yApi.token", token);
		YApiAccount.set(kv);
		try {
			if (ObjectUtil.isNotEmpty(funcNo)) {
				YApiManager.getInstance().exportByApiKey(funcNo);
			}else if (ObjectUtil.isNotEmpty(moduleKey) && ObjectUtil.isNotEmpty(systemKey)) {
				YApiManager.getInstance().export(systemKey, moduleKey);
			} else if (ObjectUtil.isNotEmpty(systemKey)) {
				YApiManager.getInstance().exportBySystemKey(systemKey);
			} else {
				throw new MFTException("不支持的导入参数");
			}
		} catch (MFTException e) {
			throw e;
		} catch (Exception e) {
			log.error("", e);
			throw new MFTException(-1, "接口导入失败,请重试[" + e.getMessage() + "]");
		} finally {
			YApiAccount.remove();
		}
		return ExecuteReturn.builder().build();
	}

	@Test
	public void test() {
		try {
			ExecutingResource<Regulation> value = new ExecutingResource<>();
			PluginFunctionTester<MFTAsExportToYapiFunction, ExecutingResource<Regulation>> functionTester = new PluginFunctionTester<MFTAsExportToYapiFunction, ExecutingResource<Regulation>>(
					MFTAsExportToYapiFunction.class, value);
			// PluginFunctionTester<MFTApiRuntimeFunction> functionTester = new
			// PluginFunctionTester<>(MFTApiRuntimeFunction.class);
			functionTester.addField("loginId", "changjian1988@yeah.net");
			functionTester.addField("pass", "changjian1988");
			functionTester.addField("systemKey", "mftDev");

			// StockRedisAccess dd= MFTSpringUtil.getBean("s0051",StockRedisAccess.class);
			// MFTSpringUtil.getBean(sysNo, classType);
			functionTester.testInvoke();
		} catch (Throwable e) {
			log.error("", e);
		}

	}
}
